package com.smzd.framework.utils.db;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.smzd.core.domain.IntIdEntity;
import com.smzd.core.utils.db.Page;

/**
 * RPage: 特别为Flexigrid前台组件设计的查询器，要求对象都是IntIdEntity
 * 
 * @author yuzhongda
 * 
 * @param <E>
 *            elems类型参数
 */
public class RPage<E extends IntIdEntity> extends Page<E> {

	private FGRowConverter<E> converter;

	public String toFlexiGridJsonString(FGRowConverter<E> converter) {
		this.converter = converter;
		return toFlexiGridJsonString();
	}

	protected Object[] convertElementInJson(E elem) {
		return converter.convert(elem);
	}

	protected Integer getElemId(E elem) {
		return elem.getId();
	}

	protected String toFlexiGridJsonString() {
		JSONArray arr = new JSONArray();
		for (E elem : this.getElems()) {
			JSONObject row = new JSONObject();
			row.accumulate("id", getElemId(elem));
			JSONArray fs = new JSONArray();
			Object[] values = convertElementInJson(elem);
			for (Object value : values) {
				fs.add(value);
			}
			row.accumulate("cell", fs);
			arr.add(row);
		}
		JSONObject json = new JSONObject();
		json.accumulate("page", getPageNo());
		json.accumulate("total", getTotalCount());
		json.accumulate("rows", arr);
		return json.toString();
	}
}
